<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;

class UserController extends Controller
{
    public function __construct()
    {
        //只允许登录后访问，except表示未登录也可访问
        $this->middleware('auth', [
            'except' => ['show', 'create', 'store', 'index']
        ]);

        //只允许游客访问的操作
        $this->middleware('guest', [
            'only' => ['create']
        ]);
    }

    public function index()
    {
        $users = User::all();
        return view('users.index', compact('users'));
    }

    public function create()
    {
        return view('users.create');
    }

    public function show(User $user, Request $request)
    {
        $count = $user->statuses()->count();
        $curr = $request->page ? $request->page : 1;
        $statuses = $user->statuses()
                        ->orderBy('created_at', 'desc')
                        ->paginate(5);
        return view('users.show', compact('user', 'statuses', 'curr', 'count'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:3|max:50',
            'email' => 'required|email|unique:users|max:255',
            'password' => 'required|confirmed|min:6'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);
        Auth::login($user);
        session()->flash('success', '恭喜，注册成功！');
        return redirect()->route('users.show', [$user]);
    }

    //编辑用户
    public function edit(User $user)
    {
        //检查是否有权限编辑
        $this->authorize('update', $user);
        return view('users.edit', compact('user'));
    }

    public function update(User $user, Request $request)
    {
        //检查是否有权限更新
        $this->authorize('update', $user);
        $this->validate($request, [
            'name' => 'required|min:3|max:50',
            'password' => 'nullable|confirmed|min:6'
        ]);
        $data['name'] = $request->name;
        if($request->password)
            $data['password'] = $request->password;
        $user->update($data);
        session()->flash('success', '资料更新成功');
        return redirect()->route('users.show', $user->id);
    }

    // public function destroy(User $user)
    // {
    //     $user->delete();
    //     session()->flash('success', '成功删除用户！');
    //     return back();
    // }

    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (!is_array($ids) || empty($ids)){
            return Response::json(['code'=>1,'msg'=>'请选择删除项']);
        }
        try{
            $this->authorize('destroy-users');
            User::destroy($ids);
            return Response::json(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            return Response::json(['code'=>1,'msg'=>'删除失败']);
        }
    }



    public function data(Request $request)
    {
        $query = DB::table('users');
        $res = $query->paginate($request->get('limit', 30))->toArray();
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res['data']
        ];
        return response()->json($data);
    }

    public function followings(User $user, Request $request)
    {
        $curr = $request->page ? $request->page : 0;
        $count = $user->followings()->count();
        $users = $user->followings()->paginate(10);
        $title = $user->name . '关注的人';
        $action = 'followings';
        return view('users.show_follow', compact('users', 'title', 'curr', 'count', 'action'));
    }

    public function followers(User $user, Request $request)
    {
        $curr = $request->page ? $request->page : 0;
        $count = $user->followers()->count();
        $users = $user->followers()->paginate(10);
        $title = $user->name . '的粉丝';
        $action = 'followers';
        return view('users.show_follow', compact('users', 'title', 'curr', 'count', 'action'));
    }
}
